﻿using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using Newtonsoft.Json.Serialization;

namespace Magic.Core;

/// <summary>
/// 序列化配置
/// </summary>
public static class NewtonsoftJsonExtensions
{
    public static IMvcBuilder AddJson(this IMvcBuilder builder)
    {

        var jsonSerializerSettings = new JsonSerializerSettings
        {
            // 首字母小写(驼峰样式)
            ContractResolver = new CamelCasePropertyNamesContractResolver(),
            // 时间格式化
            DateFormatString = "yyyy-MM-dd HH:mm:ss",
            // 忽略循环引用
            ReferenceLoopHandling = ReferenceLoopHandling.Ignore
        };

        JsonConvert.DefaultSettings = () => jsonSerializerSettings;

        builder.AddNewtonsoftJson(options =>
        {
            // 首字母小写(驼峰样式)
            options.SerializerSettings.ContractResolver = jsonSerializerSettings.ContractResolver;
            // 时间格式化
            options.SerializerSettings.DateFormatString = jsonSerializerSettings.DateFormatString;
            // 忽略循环引用
            options.SerializerSettings.ReferenceLoopHandling = jsonSerializerSettings.ReferenceLoopHandling;
            // 忽略空值
            //options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore;
        });
        return builder;
    }
}
